<style lang="scss">
// @import '@/assets/css/variable';

</style>

<template>
  <div class="wrapperContent2" style="padding-bottom: 86px;">
	<van-form validate-first @failed="onFailed" @submit="onSubmit" :show-error-message="false" label-width="112">
		<div class="fc-333 titleLabel flex align-center justify-between pad-r-10">
			<div>个人基本信息</div>
			<van-button class="fs-12 padding-lr" color="linear-gradient(to bottom, #6FC6FC, #1FA0F5)" round native-type="submit" size="mini">
			  保 存
			</van-button>
		</div>
	    <van-field :size="fontSize==1?'':'large'" v-model="form.member_name" name="member_name" required maxlength="18" label="姓名" placeholder="请填写姓名" right-icon="edit" :rules="[{ required: true, message: '请填写姓名' }]" @blur="checkAllTextValid('member_name',form.member_name)"/>
		<van-field :size="fontSize==1?'':'large'" v-model="form.member_mobile" label="手机号" name="member_mobile" text='number' required placeholder="请填写手机号" readonly/>
		<van-field :size="fontSize==1?'':'large'" v-model="form.card_no" name="card_no" required maxlength="18" label="身份证号" placeholder="请填写身份证号" @blur="cardNoBlur" right-icon="edit" :rules="[{ required: true, message: '请填写身份证号' }]"/>
		<van-field :size="fontSize==1?'':'large'" v-model="form.gender" name="gender" required label="性别" placeholder="填写身份证号后自动生成" readonly></van-field>
		<van-field :size="fontSize==1?'':'large'" v-model="form.birthday" name="birthday" required label="生日" placeholder="填写身份证号后自动生成" readonly/>
		<van-field :size="fontSize==1?'':'large'" v-model="form.age" label="年龄" required placeholder="填写身份证号后自动生成" readonly/>
		<van-field :size="fontSize==1?'':'large'" v-model="form.card_address_str" name="card_address_str" required label="籍贯" placeholder="填写身份证号后自动生成" readonly/>
		<van-field :size="fontSize==1?'':'large'" v-model="form.identity_str" name="identity"required @click="showIdentity = true" maxlength="24" label="企业类型" placeholder="请选择企业类型" right-icon="arrow" readonly :rules="[{ required: true, message: '请选择企业类型' }]"/>
	    <van-action-sheet v-model="showIdentity" :actions="memverConfig.identity" @select="onSelectIdentity" cancel-text="取消"/>
		<van-field :size="fontSize==1?'':'large'" v-model="form.record_record_str" name="record_record" required @click="showRecord = true" label="信用记录" placeholder="请选择信用记录" right-icon="arrow" readonly :rules="[{ required: true, message: '请选择信用记录' }]"/>
		<van-action-sheet v-model="showRecord" :actions="memverConfig.recordRecord" @select="onSelectRecord" cancel-text="取消"/>
		<van-field :size="fontSize==1?'':'large'" name="is_delict" required label="违法行为" placeholder="是否有违法行为" :rules="[{ required: true, message: '请选择是否有违法行为' }]">
			<template #input>
			  <van-radio-group v-model="form.is_delict" name="is_delict" direction="horizontal">
			    <van-radio name="1">是</van-radio>
			    <van-radio name="2">否</van-radio>
			  </van-radio-group>
			</template>
		</van-field>
		<van-field :size="fontSize==1?'':'large'" v-model="form.person_types_str" required @click="showPersonTypes = true" rows="2" type="textarea" autosize label="重点人群" placeholder="法人是否为重点人群" right-icon="arrow" readonly :rules="[{ required: true, message: '法人是否为重点人群'}]"/>
		<van-action-sheet v-model="showPersonTypes" :actions="memverConfig.zdrq" @select="onSelectPersonType" cancel-text="取消"/>
		<div v-if="form.identity_key=='company'||form.identity_key=='pty'||form.identity=='company'||form.identity=='pty'">
			<div class="fc-333 titleLabel">(企业/个体户)信息</div>
			<van-field :size="fontSize==1?'':'large'" v-model="form.company_name" required name="company_name" maxlength="30" label="企业名称" placeholder="请填写企业名称" right-icon="edit" :rules="[{ required: true, message: '请填写企业名称'}]" @blur="checkAllTextValid('company_name',form.company_name)"/>
			<van-field :size="fontSize==1?'':'large'" v-model="form.valid_start_time" required name="valid_start_time" maxlength="30" label="企业注册日期" placeholder="请填写企业注册日期" @click="showStartTimePop = true" right-icon="arrow" readonly :rules="[{ required: true, message: '请填写企业注册日期'}]"/>
			<van-popup
			  v-model="showStartTimePop"
			  position="bottom"
			  >
			  <div>
				  <van-datetime-picker
				    v-model="currentDate"
				    type="date"
				    title="选择年月日"
				    :min-date="minDate"
				    :max-date="maxDate"
					@cancel="showStartTimePop = false"
					@confirm="confirmStartTime"
				  />
			  </div>
			</van-popup>
			<van-field :size="fontSize==1?'':'large'" v-model="form.legal_person_name" name="legal_person_name" required maxlength="20" label="法定代表人" placeholder="请填写法定代表人姓名" right-icon="edit" :rules="[{ required: true, message: '请填写法定代表人姓名'}]" @blur="checkAllTextValid('legal_person_name',form.legal_person_name)"/>
			<van-field :size="fontSize==1?'':'large'" v-model="form.legal_person_mobile" name="legal_person_mobile" required type="number" maxlength="11" label="法人手机号" placeholder="请填写法人手机号" right-icon="edit" :rules="[{ required: true, message: '请填写法人手机号'}]" @blur="checkAllTextValid('legal_person_mobile',form.legal_person_mobile)"/>
			
			<van-field :size="fontSize==1?'':'large'" v-model="form.social_credit_code" required name="social_credit_code" maxlength="18" label="统一社会信用代码" placeholder="请填写18位统一社会信用代码" right-icon="edit" :rules="[{ required: true, message: '请填写统一社会信用代码'}]" @blur="checkAllTextValid('social_credit_code',form.social_credit_code)"/>
			<van-field :size="fontSize==1?'':'large'" v-model="form.company_people_num" required name="company_people_num" maxlength="8" label="企业人数" placeholder="请填写企业人数" right-icon="edit" type="digit" :rules="[{ required: true, message: '请填写企业人数'}]"/>
		</div>
		
		<div v-if="diyField.length">
			<div class="fc-333 titleLabel flex align-center justify-between pad-r-10">
				<div>其他信息</div>
				<van-button class="fs-12 padding-lr" color="linear-gradient(to bottom, #6FC6FC, #1FA0F5)" round native-type="submit" size="mini">
				  保 存
				</van-button>
			</div>
			<div v-for="(item,index) in diyField">
				<!-- <van-radio-group v-model="item.field_value" name="field_value" direction="horizontal">
				  <van-radio v-for="it in item.input_key_value" :name="it" @click="changeAAA">{{it}}</van-radio>
				</van-radio-group> -->
				<van-field :size="fontSize==1?'':'large'" required label-width="100px" v-if="item.input_type=='radio'" :label="item.field_label" @click="changeAAA" :rules="[{ required: true, message: '请完善信息'}]">
					<template #input>
					  <van-radio-group v-model="item.field_value" :name="item.field_value" direction="horizontal">
					    <van-radio v-for="(it,index) in item.input_key_value" :name="it" :key="index"><span style="line-height: 2em;">{{it}}</span></van-radio>
					  </van-radio-group>
					</template>
				</van-field>
				<van-field :size="fontSize==1?'':'large'" required label-width="100px" v-if="item.input_type=='number'" :label="item.field_label" v-model="item.field_value" :name="item.field_value" type="number" right-icon="edit" placeholder="请填写信息" @blur="blurChange(item,index)">
				</van-field>
				<van-field :size="fontSize==1?'':'large'" required label-width="100px" v-if="item.input_type=='checkbox'" :label="item.field_label" @click="changeAAA" :rules="[{ required: true, message: '请完善信息'}]">
					<template #input>
					  <van-checkbox-group v-model="item.field_value" :name="item.field_value" direction="horizontal">
					    <van-checkbox v-for="(it,index) in item.input_key_value" :name="it" shape="square" :key="index"><span style="line-height: 2em;">{{it}}</span></van-checkbox>
					  </van-checkbox-group>
					</template>
				</van-field>
			</div>
		</div>
	  <!-- <div class="fixed_bottom">
	    <van-button class="fs-15" color="linear-gradient(to bottom, #6FC6FC, #1FA0F5)" round block native-type="submit">
	      保 存
	    </van-button>
	  </div> -->
	</van-form>
	
  </div>
</template>
<script>
import { Toast,Dialog  } from 'vant';
import { mapGetters, mapActions } from "vuex";
export default {
	name:'editUserInfo',
  components: {},
  data() {
    return {
		minDate: new Date(1949, 0, 1),
		maxDate: new Date(),
		currentDate: new Date(2012, 0, 1),
		showStartTimePop:false,
		value1: '',
		value2: '',
		value3: '',
		pattern: /\d{6}/,
		form:{
			// 个人基础信息
			member_name:'',
			gender:'',
			card_no:'',
			birthday:'',
			identity:'',
			person_types:'',
			card_address_str:'',
			card_province_id:'',
			card_city_id:'',
			card_area_id:'',
			is_delict:'',
			record_record:'',
			age:'',
			// 企业信息
			company_name:'',
			legal_person_name:'',
			social_credit_code:'',
			legal_person_mobile:'',
			company_people_num:''
		},
		formDiy:[
			{
				field_default_value: false,
				field_label: "家庭年收入(万)",
				field_name: "afe04fe9-4369-4480-8fe9-c321da819f83",
				field_value: "20",
				group: "diy",
				input_key_value: [],
				input_type: "number",
				type: "diy",
			},
			{
				field_default_value: false,
				field_label: "是否为大学生",
				field_name: "ecb845a6-4534-4c95-8ed3-f230137133fc",
				field_value: "否",
				group: "diy",
				input_key_value: ["是","否"],
				input_type: "radio",
				type: "diy"
			},
			{
				field_default_value: false,
				field_label: "兴趣爱好",
				field_name: "f8108348-ff24-4955-8f28-7e21321957bf",
				field_value: ["睡觉", "吃饭"],
				group: "diy",
				input_key_value: ["睡觉", "吃饭", "打豆豆"],
				input_type: "checkbox",
				type: "diy"
			}
		],
		returnData:{},
		basicField:[],//基本表单
		companyField:[],//企业表单
		diyField:'',//企业表单
		actionsIDentity: [{ name: '企业' }, { name: '个人' }, { name: '个体户' }],
		actionsPersonType:[{ name: '无' }, { name: '招用在校大学生和毕业5年以内高校毕业生' }, { name: '登记失业半年以上人员、就业困难人员' }, {name:'自主择业军转干部和自主就业退役士兵'}, {name:'持证残疾人'}],
		actionsRecord:[{name:'暂无'}],
		showIdentity:false,
		showPersonTypes:false,
		showRecord:false,
		memverConfig:'',
		fontSize:localStorage.getItem('fontSize') || 1
    };
  },
  created() {
	console.log('created')
	this.getMemberConfig()
	this.getAllMember()
    // this.initItemData();
  },
  computed: {
    ...mapGetters(['member']),
  },
  mounted() {
	  console.log('mounted')
	 //  this.bus.$on('getAllMember',()=>{
		// this.getAllMember()  
	 //  })
  },
  beforeDestroy() {
  	// this.bus.$off('getAllMember')
  },
  methods:{
	  ...mapActions(['GET_AllMember']),
	   checkAllTextValid(type,val) {
		 var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]")
		 console.log('pattern.test(val)',pattern.test(val))
		 if(pattern.test(val)){
			 Dialog({ title:'温馨提示', message: '所填信息中不得含有特殊字符', closeOnClickOverlay:true });
			 return;
		 }
		 if(type=='member_name'){
			
		 }else if(type=='legal_person_mobile'){
			 if(!this.$reg.phone.test(val)){
				 Dialog({ title:'温馨提示', message: '请填写正确手机号', closeOnClickOverlay:true });
				 return;
			 }
		 }
		 
	  },
	  blurChange(item,index) {
		  // this.checkAllTextValid('',item.field_value)
		  console.log('item',item,index)
		  this.diyField[index].field_value = item.field_value
		  this.$forceUpdate()
	  },
	  changeAAA(e) {
		  console.log('value',e.target.innerText)
		  setTimeout(()=>{
			  this.$forceUpdate()
		  },100)
	  },
	  blurPeopleNum() {
		  console.log('peopleNum',this.form.company_people_num)
	  },
	  confirmStartTime(val) {
		  this.form.valid_start_time = this.$utils.parseToDateYMD(val)
		  this.showStartTimePop = false
	  },
	  onSubmit(values) {
		var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]")
		if(pattern.test(this.form.member_name)){
			 Dialog({ title:'温馨提示', message: '姓名中不得含有特殊字符', closeOnClickOverlay:true });
			 return;
		}
		if(!this.$reg.idCard.test(this.form.card_no)) {
			Dialog({ title:'温馨提示', message: '身份证格式有误', closeOnClickOverlay:true });
			return
		}
		console.log('this.form.is_delict',this.form.is_delict)
		if(this.form.is_delict!=1&&this.form.is_delict!=2) {
			 Dialog({ title:'温馨提示', message: '请选择是否有违法行为', closeOnClickOverlay:true });
			 return
		}
		if(this.form.identity == 'person'){
			
		}else{
			// if(pattern.test(this.form.company_name)){
			// 	 Dialog({ title:'温馨提示', message: '企业名称中不得含有特殊字符', closeOnClickOverlay:true });
			// 	 return;
			// }
			// if(pattern.test(this.form.legal_person_name)){
			// 	 Dialog({ title:'温馨提示', message: '企业法人字段中不得含有特殊字符', closeOnClickOverlay:true });
			// 	 return;
			// }
			// if(!this.$reg.social_credit_code.test(this.form.social_credit_code)) {
			// 	 Toast('请正确填写18位统一社会信用代码') 
			// 	 return
			// }
			// if(pattern.test(this.form.social_credit_code)){
			// 	 Dialog({ title:'温馨提示', message: '统一社会信用代码中不得含有特殊字符', closeOnClickOverlay:true });
			// 	 return;
			// }
		}
		
	  	values.id = this.member.id
	  	// this.form.card_province_id = res.data.areaData.province.id
	  	// this.form.card_city_id = res.data.areaData.city.id
	  	// this.form.card_area_id = res.data.areaData.area.id
		values.gender = this.form.gender=='男'?1:2
	  	values.card_province_id = this.form.card_province_id
	  	values.card_city_id = this.form.card_city_id
	  	values.card_area_id = this.form.card_area_id
	  	values.record_record = this.form.record_record_key || this.form.record_record
	  	values.identity = this.form.identity_key || this.form.identity
		values.person_types = this.form.person_types_key || this.form.person_types
	  	values.diys = []
	  	let diyItem = {}
	  	this.diyField.forEach(item=>{
	  		// values[item.field_name] = item.field_default_value
	  		diyItem = {
	  			policy_diy_id: item.field_name,
	  			policy_diy_value: item.field_value
	  		}
	  		values.diys.push(diyItem)
	  	})
		let isNull = false
		// values.diys.forEach(item=>{
		// 	if(!item.policy_diy_value){
		// 		isNull = true
		// 	}
		// })
		console.log('isNull',isNull)
		if(isNull==true){
			Dialog.alert({
			  title: '温馨提示',
			  message: '请完善信息',
			}).then(() => {
			  // on close
			});
			return
		}
		console.log('values',values)
	  	this.$request.saveMemberInfo(values).then(res=>{
	  		if(res.code == 200) {
	  			Dialog.alert({
	  			  title: '温馨提示',
	  			  message: '保存成功',
	  			}).then(() => {
	  			  // on close
	  			  this.getAllMember()
				  // this.$router.go(-1)
	  			});
	  		}
	  	})
	  },
	  getAllMember() {
		  this.GET_AllMember().then(res=>{
			  console.log('GET_Member__res',res)
			  if(res.code == 200) {
				const company = res.data.company
				this.form = Object.assign({},this.form,res.data)
				if(this.form.card_no){
					this.form.age = this.$utils.calculateAge(this.form.card_no)
				}
				this.form.is_delict = this.form.is_delict.toString() // .toString()
				this.form.company_name = res.data.company?res.data.company.company_name:''
				this.form.legal_person_name = res.data.company?res.data.company.legal_person_name:''
				this.form.social_credit_code = res.data.company?res.data.company.social_credit_code:''
				this.form.valid_start_time = res.data.company?res.data.company.valid_start_time:''
				this.form.legal_person_mobile = res.data.company?res.data.company.legal_person_mobile:''
				this.form.company_people_num = res.data.company?res.data.company.company_people_num:''
				if(res.data.company&&res.data.company.valid_start_time){
					this.currentDate = new Date(res.data.company.valid_start_time)
				}
				this.$store.commit('setMember',this.form)
				this.form.gender = res.data.gender==1?'男':'女'
				// this.diys = this.form.diys.list
				// this.$forceUpdate()
				// 获取自定义表单
				this.getInputMemberFields();
			  }
		  })
	  },
	  getInputMemberFields() {
		  this.$request.getInputMemberFields().then(res=>{
			// console.log('res',res)
			this.returnData = res.data
			var diyField = []
			// let diyField =new Set();//搜索结果集合
			for(let key in this.returnData){
				if(this.returnData[key].group=='diy'){
					if(this.returnData[key].input_type=='checkbox'){
						this.returnData[key].field_value = []
					}else{
						this.returnData[key].field_value = ''
					}
					diyField.push(this.returnData[key])
				}
			}
			console.log('===diyField===',diyField)
			console.log('===this.form===',this.form)
			// for(let item of diyField) {
			//   console.log('item——set',item);
			//   this.form.diys.list.forEach(jItem => {
			//   	if(jItem.policy_diy_id==item.field_name){
			//   		if(item.input_type=='checkbox'){
			//   			item.field_value = (jItem.policy_diy_value&&jItem.policy_diy_value.split(',')) || []
			//   			console.log('___item____',item)
			//   		}else{
			//   			item.field_value = jItem.policy_diy_value
			//   		}
			//   		return item
			//   	}
			//   })
			// }
			diyField.map(item=>{
				this.form.diys.list.forEach(jItem => {
					if(jItem.policy_diy_id==item.field_name){
						if(item.input_type=='checkbox'){
							item.field_value = (jItem.policy_diy_value&&jItem.policy_diy_value.split(',')) || []
							console.log('___item____',item)
						}else{
							item.field_value = jItem.policy_diy_value
						}
						return item
					}
				})
			})
			this.diyField = diyField
			console.log('this.diyField',this.diyField)
			// this.diyField = this.formDiy
			// this.form.diys = this.diyField
			console.log('this.form.diys',this.form.diys)
		  })
	  },
	  // 获取会员完善信息的配置项
	  getMemberConfig() {
		  this.$request.getMemberConfig().then(res=>{
			  this.memverConfig = res.data
			  for(let key in this.memverConfig){
			     this.memverConfig[key].map(item=>{
					  item.name = item.value
					  return item
				  })
			   }
			  // this.memverConfig.recordRecord.map(item=>{
				 //  item.name = item.value
				 //  return item
			  // })
			  console.log('this.memverConfig',this.memverConfig)
		  })
	  },
	  cardNoBlur() {
		  if(!this.$reg.idCard.test(this.form.card_no)) {
			 Toast('身份证格式有误') 
			 return
		  }
		  if(this.form.card_no){
			  this.form.age = this.$utils.calculateAge(this.form.card_no)
		  }
		  
		  const params = {
			  cardNo:this.form.card_no
		  }
		  this.$request.analysisCardNo(params).then(res=>{
		  	console.log('analysisCardNo__res',res.data)
		  	if(res.code == 200) {
		  		this.form.gender = res.data.gender==1?'男':'女'
				this.form.birthday = `${res.data.birthday.year}/${res.data.birthday.month}/${res.data.birthday.day}`
				this.form.card_address_str = `${res.data.areaData.province.areaname}/${res.data.areaData.city.areaname}/${res.data.areaData.area.areaname}`
				this.form.card_province_id = res.data.areaData.province.id
				this.form.card_city_id = res.data.areaData.city.id
				this.form.card_area_id = res.data.areaData.area.id
				// this.form.card_city_id =  
				// this.form.card_area_id =  
		  	}
		  })
	  },
	  onSelectPersonType(item) {
		// 默认情况下点击选项时不会自动收起
		// 可以通过 close-on-click-action 属性开启自动收起
		this.showPersonTypes = false;
		// Toast(item.name);
		this.form.person_types_str = item.name
		this.form.person_types_key = item.key
	  },
	  onSelectIdentity(item) {
		// 默认情况下点击选项时不会自动收起
		// 可以通过 close-on-click-action 属性开启自动收起
		this.showIdentity = false;
		// Toast(item.name);
		this.form.identity_str = item.name
		this.form.identity_key = item.key
		this.form.identity = item.key
		console.log('this.form.identity_str',this.form.identity_str)
		console.log('this.form.identity_key',this.form.identity_key)
		console.log('this.form.identity',this.form.identity)
	  },
	  onSelectRecord(item) {
		  console.log('item',item)
	  		// 默认情况下点击选项时不会自动收起
	  		// 可以通过 close-on-click-action 属性开启自动收起
	  		this.showRecord = false;
	  		// Toast(item.name);
	  		this.form.record_record_str = item.name
			this.form.record_record_key = item.key
	  },
	  isShowCompanyField(key){
	  		return this.companyField.indexOf(key)
	  },
	  isShowBasicField(key){
		return this.basicField.indexOf(key)
	  },
    // 校验函数返回 true 表示校验通过，false 表示不通过
	validator(val) {
	  return /1\d{10}/.test(val);
	},
	// 异步校验函数返回 Promise
	asyncValidator(val) {
	  return new Promise((resolve) => {
		Toast.loading('验证中...');

		setTimeout(() => {
		  Toast.clear();
		  resolve(/\d{6}/.test(val));
		}, 1000);
	  });
	},
	onFailed(errorInfo) {
	  console.log('failed', errorInfo);
	  Toast(errorInfo.errors[0].message)
	},
  }
}

</script>